import datetime

from ajson import aj
from flask import request, Response

from db_base import ArticleOrm, ClassificationOrm, UserOrm, StarOrm, CommentOrm, MyFactory
from utils import Error
from . import admin_v
from .util import BarEcharts, PieEcharts
from ..view_util import MyView


@admin_v.route('/visual/sum/')
def visual_sum():
    """
    最近七天的发帖数量
    """
    dates = [datetime.datetime.now() - datetime.timedelta(days=i) for i in range(7)]

    sums = []
    for i in dates:
        gt_time = i - datetime.timedelta(hours=i.hour, minutes=i.minute, seconds=i.second,
                                         microseconds=i.microsecond)

        lt_time = gt_time + datetime.timedelta(hours=24)

        article_seven = ArticleOrm.orm.find() \
            .where(create_time__gt=gt_time,
                   create_time__lt=lt_time, ) \
            .end()
        count = len(article_seven)
        sums.append(count)

    line = BarEcharts(xData=[i.strftime('%Y-%m-%d') for i in dates], yData=sums, title='最近七天的发帖数量')
    return Response(aj.parse(line), status=200)


def cf_echarts():
    cfs = ClassificationOrm.orm.find().end()

    xData = [i.name for i in cfs]

    yData = []

    for i in cfs:
        a = ArticleOrm.orm.find().where(classification_id=i.id).end()
        yData.append(len(a))

    return xData, yData


@admin_v.route('/visual/cfsum/')
def visual_cf_sum():
    """
    每个类别的发帖数量统计
    """
    # 先取出所有的分类
    xData, yData = cf_echarts()

    line = BarEcharts(xData=xData, yData=yData, title='每个类别的发帖数量统计')
    return Response(aj.parse(line), status=200)


@admin_v.route('/visual/pie/')
def visual_cf_pie():
    """
    每个类别的发帖占比统计
    """
    # 先取出所有的分类
    xData, yData = cf_echarts()

    data = [{'value': v, 'name': n} for n, v in zip(xData, yData)]

    line = PieEcharts(data=data, title='发帖占比统计')
    return Response(aj.parse(line), status=200)


@admin_v.route('/visual/comment/')
def visual_cf_comment():
    """
    每个类别的评论数量统计
    """
    # TODO:这个sql有点复杂，我就不解释了
    sql = """
SELECT classification_id AS cf_id,
         s_count cf_comment_count,
         cf.`name` AS cf_name
FROM 
    (SELECT classification_id,
         sum(count) AS s_count
    FROM 
        (SELECT article_id,
         COUNT( article_id ) AS count
        FROM article_comment
        WHERE article_id IN 
            (SELECT id
            FROM `article` )
            GROUP BY  article_id ) AS a
            LEFT JOIN article cp_a
                ON a.article_id = cp_a.id
            GROUP BY  classification_id ) AS b
        LEFT JOIN classification AS cf
        ON b.classification_id=cf.id
    """

    # 将所有的类被查出来以防漏掉
    all_cf = ClassificationOrm.find_all()
    data = []
    for i in all_cf:
        # 默认设置为没有评论
        data.append({
            'name': i.name,
            'value': 0
        })

    ss = ClassificationOrm.find_sql(sql=sql)
    for i in ss:
        for j, v in enumerate(data):
            if v['name'] == i.cf_name:
                data[j]['value'] = int(i.cf_comment_count)
                break

    line = PieEcharts(data=data, title='评论占比统计')
    return Response(aj.parse(line), status=200)


@admin_v.route('/user_list/')
def all_user():
    """
    所有的用户
    """
    data = request.args
    u_type = int(data.get('u_type') if data.get('u_type') else 0)
    if u_type != 1:
        return Error('禁止访问,权限不足', 403)
    page = int(data.get('page'))
    limit = int(data.get('limit'))

    user_list = UserOrm.orm.find().end()

    count = len(user_list)
    page_data = user_list.page(limit)
    if len(page_data) >= page:
        page_data = page_data.get(page - 1)

    else:
        return Error('没有更多了', 400)

    result = {
        'total': count,
        'data': page_data.to_dict(),
        'listQuery': {
            'page': page,
            'limit': limit
        }
    }
    return Response(aj.parse(result), status=200)


@admin_v.route('/update/', methods=['POST'])
def update():
    data = aj.load(request.get_data(as_text=True))
    email = data['email']
    data.pop('user_id')
    line = UserOrm.orm.update().set(**data).where(email=email).end()
    item = UserOrm.orm.find().where(email=email).first().end()

    return Response(item.to_json(), status=200)


class ArticleView(MyView):

    def post(self):
        data = self.get_data()
        article_id = int(data['article_id'])
        s_line = StarOrm.orm.delete().where(article_id=article_id).end()
        c_line = CommentOrm.orm.delete().where(article_id=article_id).end()
        a_line = ArticleOrm.orm.delete().where(id=article_id).end()
        print(s_line + c_line + a_line)

        return Response(aj.parse(s_line + c_line + a_line), status=200)

    def put(self):
        data = self.get_data()
        line, last_id = ArticleOrm.orm.update().set(**data).where(id=data['id']).end()
        item = MyFactory.createInstance('article.Article', **data)

        result = {
            'data': item.to_dict(),
            'code': 200,
            'message': 'ok'
        }
        return Response(aj.parse(result), status=200)


class CfView(MyView):

    def post(self):
        data = self.get_data()
        line, last_id = MyFactory.createInstance('article.Classification', **data).save()
        item = ClassificationOrm.orm.find().where(id=last_id).first().end()
        return Response(item.to_json(), status=200)

    def put(self):
        data = self.get_data()
        line, last_id = ClassificationOrm.orm.update().set(**data).where(id=data['id']).end()
        item = MyFactory.createInstance('article.Classification', **data)

        result = {
            'data': item.to_dict(),
            'code': 200,
            'message': 'ok'
        }
        return Response(aj.parse(result), status=200)

    def delete(self):
        data = self.get_args()
        cf_id = int(data['id'])
        # 先获取所有这个类别的帖子id
        a_ids_qs = ClassificationOrm.orm.find().where(id=cf_id).end()
        ids = [i.id for i in a_ids_qs]

        if ids and len(ids) > 0:
            s_line = StarOrm.orm.delete().where(article_id__in=ids).end()
            c_line = CommentOrm.orm.delete().where(article_id__in=ids).end()
            a_line = ArticleOrm.orm.delete().where(id__in=ids).end()
            cf_line = ClassificationOrm.orm.delete().where(id=data['id']).end()
            print(s_line + c_line + a_line + a_line + cf_line)

            return Response(aj.parse(s_line + c_line + a_line + cf_line), status=200)
        return Error('找不到分类', 400)


admin_v.add_url_rule('/updateArticle/', view_func=ArticleView.as_view('updateArticle'))
admin_v.add_url_rule('/updateCf/', view_func=CfView.as_view('updateCf'))
